package com.db;

import com.jfinal.config.Plugins;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.vvss.jfinal.Elephant;
import lombok.experimental.UtilityClass;
import lombok.extern.log4j.Log4j;
import org.beetl.sql.core.*;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.experimental.iohao.core.SqlKit;
import org.beetl.sql.experimental.iohao.mapper.FastMapperBuilder;
import org.beetl.sql.ext.DebugInterceptor;

/**
 * <BR>
 * create time: 2017/4/17 18:00
 *
 * @author luoyizhu
 */
@UtilityClass
@Log4j
public class Config {
    boolean init;
    String userName = "orm";
    String password = "orm123ORM";
    String url = "jdbc:mysql://localhost:3306/beetlbbs?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
    String driver = "com.mysql.jdbc.Driver";


    public void dbInit() {
        if (init) {
            return;
        }

        init = true;

        ConnectionSource source = ConnectionSourceHelper.getSimple(driver, url, userName, password);

        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/sql 目录下
        SQLLoader loader = new ClasspathLoader("/sql");
        // 数据库命名跟java命名一样，所以采用DefaultNameConversion，还有一个是UnderlinedNameConversion，下划线风格的，
        NameConversion nc = new DefaultNameConversion();
        // 最后，创建一个SQLManager,DebugInterceptor 不是必须的，但可以通过它查看sql执行情况
        Interceptor[] inters = new Interceptor[]{new DebugInterceptor()};

        SQLManager sqlManager = new SQLManager(mysql, loader, source, nc, inters);

        // 自定义的映射构建器, 主要是为了方便扩展自定义注解
        sqlManager.setMapperBuilder(new FastMapperBuilder(sqlManager));

        SqlKit.$(sqlManager);

    }

    public void jfinalInit() {


        Plugins me = new Plugins();

        DruidPlugin druidPlugin = new DruidPlugin(url, userName, password, driver);
        me.add(druidPlugin);

        ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
        arp.addMapping("tb_bird", Elephant.class);
        me.add(arp);

        me.getPluginList().forEach(o -> o.start());
    }
}
